local addonName, IWonew = ...


CraftOrderClass = {}
CraftOrderClass.__index = CraftOrderClass

function CraftOrderClass:new(profession)
	local instance = setmetatable({}, CraftOrderClass)  -- Create a new object, and set its metatable to Person
	instance.profession = profession
	instance.RequestCrafterOrders_ing = false
	instance.currentRunningOrder = nil
	instance.currentOrders = nil
	instance.currentRunningOrderState = 1 -- 1:未开始 2：已接单 3：已制作 4：已完成
	instance.completed = false
	return instance
end

function CraftOrderClass:start()
	IWonew.Temp_Vars.needCraftLog = false
	
	-- 先不做锻造订单了
	-- if self.profession == Enum.Profession.Blacksmithing then
	-- 	IWonew.CreateTextFrame(80, "锻A", 240, 0)
	-- 	return
	-- end
	if self.completed then
		print("全部完成！！！！")
		return
	end

	if self.currentOrders == nil then
		print("获取订单")
		self:RequestCrafterOrders()
		return
	end
	if #self.currentOrders <= 0 then
		self.currentOrders = nil
		self.completed = true
		if self.profession == Enum.Profession.Blacksmithing then
			IWonew.CreateTextFrame(80, "锻A", 240, 0)
		end
		if self.profession == Enum.Profession.Enchanting then
			IWonew.CreateTextFrame(80, "附B", 320, 0)
		end
		return
	end
	if self.currentRunningOrder == nil and self.currentOrders and #self.currentOrders > 0 then
		self.currentRunningOrder = self.currentOrders[1]
		self.currentRunningOrderState = 1
	end
	if self.currentRunningOrder and self.currentRunningOrderState == 1 then
		C_CraftingOrders.ClaimOrder(self.currentRunningOrder.orderID, self.profession)
		self.currentRunningOrderState = 2
		print("接单")
		return
	end
	if self.currentRunningOrder and self.currentRunningOrderState == 2 then
		local craftingReagents = self:GetOrderCraftingReagents(self.currentRunningOrder)
		-- 制造
		print("craftingReagents", IWonew.TableToString(craftingReagents))
		C_TradeSkillUI.CraftRecipe(self.currentRunningOrder.spellID, 1, craftingReagents, nil, self.currentRunningOrder.orderID, false)
		self.currentRunningOrderState = 3
		print("制造")
		return
	end
	if self.currentRunningOrder and self.currentOrders and self.currentRunningOrderState == 3 then
		C_CraftingOrders.FulfillOrder(self.currentRunningOrder.orderID, "Success!!", self.profession)
		self.currentRunningOrder = nil
		self.currentRunningOrderState = 1
		table.remove(self.currentOrders, 1)
		print("完成")
	end
end

function CraftOrderClass:RequestCrafterOrders()
-- 	-- /dump C_TradeSkillUI.IsNearProfessionSpellFocus(9)
	if not C_TradeSkillUI.IsNearProfessionSpellFocus(self.profession) then
		print("不在专业焦点附近")
		return
	end
	if self.RequestCrafterOrders_ing then return end
	self.RequestCrafterOrders_ing = true
  	local request = {
		orderType = Enum.CraftingOrderType.Npc,
		searchFavorites = false,
		initialNonPublicSearch = false,
		primarySort = {
			sortType = Enum.CraftingOrderSortType.ItemName,
			reversed = false,
		},
		secondarySort = {
			sortType = Enum.CraftingOrderSortType.MaxTip,
			reversed = false,
		},
		forCrafter = true,
		offset = 0,
		profession = self.profession,
		callback = C_FunctionContainers.CreateCallback(function(result, ...)
			print("res", result, ...) -- 0, 0, false, false, 0, true
			if result == Enum.CraftingOrderResult.Ok then
				local orders = C_CraftingOrders.GetCrafterOrders()
				self.currentOrders = self:FilterCorrectOrders(orders)
				print("#currentOrders", #self.currentOrders)
				
				self.RequestCrafterOrders_ing = false
			end
		end),
	}
  C_CraftingOrders.RequestCrafterOrders(request)
end

function CraftOrderClass:FilterCorrectOrders(orders)
	print("#orders", #orders)
	local correctOrders = {}
	for i = 1, #orders do
		if self:IsOrderCorrect(orders[i]) then
			table.insert(correctOrders, orders[i])
		end
	end
	return correctOrders
end

function CraftOrderClass:IsHasImportantRewards(order)
	local hasImportantRewards = false
	local importantRewardIDs = {"224572"}
	for k = 1, #order.npcOrderRewards do
		local itemString = string.match(order.npcOrderRewards[k].itemLink, "item[%-?%d:]+")
		if IWonew.StringPartInList(itemString, importantRewardIDs) then
			hasImportantRewards = true
			break
		end
	end
	return hasImportantRewards
end

function CraftOrderClass:IsOrderCorrect(order)

	local recipeID = order.spellID
	local filterLocalRecipeList = IWonew.filterTable(WOW_Full_Recipe_List, function(item)
		return item.recipeID == order.spellID
	end)
	if #filterLocalRecipeList <= 0 then return false end

	local mustUseNpcRegentIDs = {}
	for i = 1, #filterLocalRecipeList[1].reagents do
		if filterLocalRecipeList[1].reagents[i].mustUseNpcRegent then
			table.insert(mustUseNpcRegentIDs, filterLocalRecipeList[1].reagents[i].itemID)
		end
	end
	local orderNpcReagentItemIDs = self:GetOrderNpcReagentItemIDs(order)
	local npcNotProvideRegents = IWonew.filterTable(mustUseNpcRegentIDs, function(itemID)
		return not IWonew.contains(orderNpcReagentItemIDs, itemID)
	end)
	if #npcNotProvideRegents > 0 then return false end

	local recipeInfo = C_TradeSkillUI.GetRecipeInfo(recipeID)
	if not recipeInfo then return false end
	if not recipeInfo.learned then return false end
	local craftingReagents = self:GetOrderCraftingReagents(order, true)
	local operationInfo = C_TradeSkillUI.GetCraftingOperationInfo(recipeID, craftingReagents, IWonew.getRandomString(10), false)
	if operationInfo == nil or order.minQuality > operationInfo.quality then return false end
	if self:IsHasImportantRewards(order) then return true end
	if not order.isFulfillable then return false end

	return true
end

function CraftOrderClass:GetOrderNpcReagentItemIDs(order)
	local npcProvideRegents = {}
	for i = 1, #order.reagents do
		table.insert(npcProvideRegents, order.reagents[i].reagent.itemID)
	end
	return npcProvideRegents
end

function CraftOrderClass:GetOrderCraftingReagents(order, ignoreNpcSlotItems)
	ignoreNpcSlotItems = ignoreNpcSlotItems or false
	local filterLocalRecipeList = IWonew.filterTable(WOW_Full_Recipe_List, function(item)
		return item.recipeID == order.spellID
	end)
	if #filterLocalRecipeList <= 0 then return {} end
	local localRecipeInfo = filterLocalRecipeList[1]
	local orderNpcReagentItemIDs = self:GetOrderNpcReagentItemIDs(order)
	local craftingReagents = {}
	for j = 1, #localRecipeInfo.reagents do
		
		if localRecipeInfo.reagents[j].needSlot and (ignoreNpcSlotItems or not IWonew.contains(orderNpcReagentItemIDs, localRecipeInfo.reagents[j].itemID)) then
			table.insert(craftingReagents, {
				quantity = localRecipeInfo.reagents[j].quantity,
				dataSlotIndex = localRecipeInfo.reagents[j].dataSlotIndex,
				itemID = localRecipeInfo.reagents[j].itemID
			})
		end
	end
	return craftingReagents
end

local CraftOrderClass_Blacksmithing = nil
local CraftOrderClass_Enchanting = nil

function StartAutoCrafterOrdersAction_Blacksmithing()
	if CraftOrderClass_Blacksmithing == nil then
		CraftOrderClass_Blacksmithing = CraftOrderClass:new(Enum.Profession.Blacksmithing)
	end
	-- Call a method
	CraftOrderClass_Blacksmithing:start()
end

function StartAutoCrafterOrdersAction_Enchanting()
	if CraftOrderClass_Enchanting == nil then
		CraftOrderClass_Enchanting = CraftOrderClass:new(Enum.Profession.Enchanting)
	end
	-- Call a method
	CraftOrderClass_Enchanting:start()
end


